package com.deyuanyun.pic.pig.service.impl;

import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.pig.controller.query.QueryTaskPointVO;
import com.deyuanyun.pic.pig.controller.vo.*;
import com.deyuanyun.pic.pig.controller.query.QueryListVO;
import com.deyuanyun.pic.settings.domain.base.Attachment;
import com.deyuanyun.pic.settings.domain.util.DomainCodeInterceptor;
import com.deyuanyun.pic.settings.service.base.AttachmentService;
import org.springframework.stereotype.Service;

import com.deyuanyun.pic.common.exception.PicException;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.pig.domain.TrackPointImportVO;
import com.deyuanyun.pic.pig.mapper.PigTaskMapper;
import com.deyuanyun.pic.pig.mapper.PigTaskPointMapper;
import com.deyuanyun.pic.pig.service.CleanPipeLineTrackService;

@Service
public class CleanPipeLineTrackServiceImpl implements CleanPipeLineTrackService {
    // 进行中
    private static final short statusFlag3 = 3;
    // 已完成
    private static final short statusFlag4 = 4;

    // 导出跟踪的excel的列数
    private static final int columns = 9;

    @Resource
    private PigTaskMapper pigTaskMapper;
    @Resource
    private PigTaskPointMapper pigTaskPointMapper;
    @Resource
    private AttachmentService attachmentService;

    @Override
    public List<PigTaskVO> getCleanPipeLineTrackIndex(QueryListVO vo) {
        vo.setStaus(new Integer[]{2, 3});
        return pigTaskMapper.queryPigTask(vo);
    }

    @Override
    public Map<String,Object> queryPigById(String taskId){
        Map<String,Object> map = new HashMap<String,Object>();

        QueryListVO vo = new QueryListVO();
        vo.setTaskId(taskId);
        List<PigTaskVO> list = pigTaskMapper.queryPigTask(vo);
        //转换CODE表外键ID为对应名称
        list = DomainCodeInterceptor.newProxyInstance(list);
        //得到清管任务信息
        PigTaskVO task = new PigTaskVO();
        FromPigVO from = new FromPigVO();
        ToPigVO to = new ToPigVO();
        List<Attachment> fromPigImgs = null;
        List<Attachment> toPigImgs = null;
        if (list.size() > 0) {
            task = list.get(0);
            from = pigTaskPointMapper.queryFromPigById(task.getFromPigId(), task.getId());
            //发球点图片
            if (null != from && StringUtils.isNotNullEmpty(from.getSendId())) {
                fromPigImgs = attachmentService.queryAttachment(from.getSendId());
            }
            to = pigTaskPointMapper.queryToPigById(task.getToPigId(), task.getId());
            //收球点图片
            if (null != to && StringUtils.isNotNullEmpty(to.getBackId())) {
                toPigImgs = attachmentService.queryAttachment(to.getBackId());
            }
        }
        map.put("pigTask", task);
        map.put("fromPig", from);
        map.put("toPig", to);
        map.put("fromPigImgs", fromPigImgs);
        map.put("toPigImgs", toPigImgs);

        return map;

    }

    @Override
    public List<PigTaskPointVO> queryTaskPoint(String taskId, boolean isPass) {
        PigTaskVO task = pigTaskMapper.selectByPrimaryKey(taskId);
        QueryTaskPointVO queryP = new QueryTaskPointVO();
        queryP.setTaskId(task.getId());
        queryP.setReverse(task.getIsAdverseCurrent());
        queryP.setIsPass(isPass);
        List<PigTaskPointVO> pointList = pigTaskMapper.queryTaskPointRecord(queryP);
        return pointList;
    }

    @Override
    public PigTaskPointVO queryTaskPointById(String pointId) {
        QueryTaskPointVO queryP = new QueryTaskPointVO();
        queryP.setPointId(pointId);
        List<PigTaskPointVO> pointList = pigTaskMapper.queryTaskPointRecord(queryP);
        PigTaskPointVO pointInfo = null;
        if (pointList.size() > 0) {
            pointInfo = pointList.get(0);
        }

        return pointInfo;
    }


    @Override
    public int saveTaskTrack(String taskId) {
        int num = 0;
        try {
            PigTaskVO t = pigTaskMapper.selectByPrimaryKey(taskId);
            t.setStaus(statusFlag4);
            num = pigTaskMapper.updateByPrimaryKeySelective(t);

        } catch (PicException e) {
            e.printStackTrace();
        }
        return num;
    }

    @Override
    public int importTrackPoint(List<TrackPointImportVO> finalInfo, String taskId) throws Exception {
        int count = 0;
        PigTaskVO t = pigTaskMapper.selectByPrimaryKey(taskId);
        if (ObjectUtil.isNotNullEmpty(finalInfo) && ObjectUtil.isNotNullEmpty(t)) {
            // 获取该任务在跟踪点通过记录表的记录
            QueryTaskPointVO queryP = new QueryTaskPointVO();
            queryP.setTaskId(t.getId());
            queryP.setReverse(t.getIsAdverseCurrent());
            List<PigTaskPointVO> ls = pigTaskMapper.queryTaskPointRecord(queryP);

            if (ls.size() > 0) {
                //判断excel中的数据是否是该任务对应的跟踪点数据
                boolean isAccordant = false;
                for (TrackPointImportVO impVo : finalInfo) {

                    if (StringUtils.isNotNullEmpty(impVo.getId())) {
                        for (PigTaskPointVO pointVO : ls) {
                            isAccordant = false;
                            if (impVo.getId().equals(pointVO.getId())) {
                                isAccordant = true;
                                break;
                            }
                        }
                    }
                    if (isAccordant) {
                        PigTaskPointVO tp = pigTaskPointMapper.selectByPrimaryKey(impVo.getId());
                        if (tp != null) {
                            tp.setPassTime(DateUtil.allStr2Date(impVo.getPassTime()));
                            tp.setRecrder(impVo.getRecorder());
                            tp.setCreateRemark(impVo.getRemark());
                            Double avgSpeed = this.computeAvgSpeed(t, tp);
                            tp.setAvgSpeed(avgSpeed);
                            pigTaskPointMapper.updateByPrimaryKeySelective(tp);
                            count++;
                        }
                    } else {
                        throw new NullPointerException("导入的excel模板中存在不正确的ID编号");
                    }
                }

                if (count > 0) { // 表示有跟踪点更新成功
                    //更新状态为进行中
                    t.setStaus(statusFlag3);
                    pigTaskMapper.updateByPrimaryKeySelective(t);
                }

            }
        }
        return count;
    }


    private Double computeAvgSpeed(PigTaskVO task, PigTaskPointVO point) {
        Double avgSpeed = null;
        //得到任务发球点绝对距离
        FromPigVO from = pigTaskPointMapper.queryFromPigById(task.getFromPigId(), task.getId());
        if (ObjectUtil.isNotNullEmpty(from) && from.getMileage() != null) {
            if (from.getSendBallsTime() != null && point.getPassTime() != null && point.getMileage() != null) {
                avgSpeed = (point.getMileage() - from.getMileage()) / ((point.getPassTime().getTime() - from.getSendBallsTime().getTime()) / 1000);
            }
        }
        return avgSpeed;
    }


}
